package com.ruoyi.common.shortFilter;

import java.io.File;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import com.ruoyi.common.constant.AllRequestMapping;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.project.shortUrl.cache.ShortCodeCache;
import com.ruoyi.project.shortUrl.cache.ShortCodeCacheEntity;
import com.ruoyi.project.shortUrl.config.domain.ShortConfig;
import com.ruoyi.project.shortUrl.config.enums.ShortUrlOpenWay;
import com.ruoyi.project.shortUrl.config.service.ShortConfigService;

@Order(1)
@WebFilter(filterName = "ShortUrlFilter",urlPatterns = {"/*"} )
public class ShortUrlFilter implements Filter
{
    private static final Logger log = LoggerFactory.getLogger(ShortUrlFilter.class);

	@Autowired
	private AllRequestMapping allRequestMapping;
	
	@Autowired
	private ShortConfigService shortConfigService;
	
	@Autowired
	private ShortCodeCache shortCodeCache;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String requestUrl = req.getRequestURI();
        String contextPath = req.getServletContext().getContextPath();
        
        ShortConfig icoConfig = shortConfigService.getConfig("ico_path");
        ShortConfig logoConfig = shortConfigService.getConfig("logo_path");
        ShortConfig bannerConfig = shortConfigService.getConfig("banner_path");
        ShortConfig footerpathConfig = shortConfigService.getConfig("footer_path");
        ShortConfig websignConfig = shortConfigService.getConfig("web_sign");
        
        ShortConfig footertextConfig = shortConfigService.getConfig("footer_text");
        
        request.setAttribute("web_sign", websignConfig==null?"":websignConfig.getValue());
        
        request.setAttribute("ico", getUrlPath(icoConfig, contextPath, "/favicon.ico"));
        request.setAttribute("logo", getUrlPath(logoConfig, contextPath, "/frameindex/logo.png"));
        request.setAttribute("banner", getUrlPath(bannerConfig, contextPath, "/frameindex/banner.jpeg"));
        request.setAttribute("footer", getUrlPath(footerpathConfig, contextPath, "http://img30.360buyimg.com/jr_image/jfs/t1/92602/27/122/123977/5da7d069E9f71abb0/c0a28ec46e233c2f.jpg"));
        
        request.setAttribute("footerText", footertextConfig==null?"":footertextConfig.getValue());
        
//        System.out.println(requestUrl);
        log.info("请求地址："+requestUrl);
        if(allRequestMapping.isSystemUrl(req) 
        		|| requestUrl.startsWith(Constants.RESOURCE_PREFIX) 
        		|| requestUrl.contains("swagger-ui.html") 
        		|| requestUrl.startsWith("/webjars/")
        		|| requestUrl.startsWith("/ajax")
        		|| requestUrl.startsWith("/css")
        		|| requestUrl.startsWith("/file")
        		|| requestUrl.startsWith("/fonts")
        		|| requestUrl.startsWith("/docs")
        		|| requestUrl.startsWith("/captcha/captchaImage")
        		|| requestUrl.startsWith("/i18n")
        		|| requestUrl.startsWith("/img")
        		|| requestUrl.startsWith("/js")
        		|| requestUrl.startsWith("/ruoyi")
        		|| requestUrl.startsWith("/favicon.ico")
        		|| requestUrl.startsWith("/register")
        		|| requestUrl.startsWith("/ruoyi.png")
        		|| requestUrl.startsWith("/cn")) {
        	
        	chain.doFilter(request, response);
        }else {
        	String shortCode = "";
        	if(requestUrl.startsWith("/")) {
        		shortCode = requestUrl.replaceAll("/", "");
        	}
        	
        	if(StringUtils.isNotBlank(shortCode)) {
        		log.info("判断："+shortCode);
        		ShortCodeCacheEntity shortCodeCacheEntity = shortCodeCache.get(shortCode);
            	if(shortCodeCacheEntity!=null) {
            		
            		log.info("是短号："+shortCodeCacheEntity.toString());
                    AsyncManager.me().execute(AsyncFactory.recordShortUrlinfo(req, shortCodeCacheEntity));
            		
            		//表示是shortcode
            		ShortUrlOpenWay openWay = ShortUrlOpenWay.getEnum(shortCodeCacheEntity.getOpenWay());
            		switch (openWay) {
            		case FRAME:
            			req.getRequestDispatcher("/cn/to/"+shortCode).forward(req,resp);
            			return;
    				default:
    					resp.sendRedirect(shortCodeCacheEntity.getTargetUrl());
    					return;
    				}
            		
            	}
        	}
        	
        	chain.doFilter(req, resp);
        }
    }
    
    private String getUrlPath(ShortConfig config, String contextPath, String defaultUrl) {
    	String url = "";
    	if(config!=null && StringUtils.isNotBlank(config.getValue())) {
        	String path = config.getValue().trim();
        	if(path.startsWith("http")) {
        		url = path;
        	}else {
        		File file = new File(path);
            	if(file.exists()) {
            		url = contextPath+"/cn/img?imgType="+config.getKey();
            	}
        	}
        }else {
        	if(defaultUrl.startsWith("http")) {
        		url = defaultUrl;
        	}else {
        		url = contextPath+defaultUrl;
        	}
        }
    	
    	return url;
    }
}
